package org.internna.expensetracker.mvc;

import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.io.ByteArrayInputStream;
import org.internna.expensetracker.model.qif.Message;
import org.internna.expensetracker.model.FinancialInstitution;
import org.internna.expensetracker.model.security.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.internna.expensetracker.services.QIFImporterService;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@Controller
@RequestMapping("/financial/qif/**")
public class QIFController {

	@Autowired private QIFImporterService qifService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

    @RequestMapping
    public String index(ModelMap modelMap) {
    	UserDetails user = UserDetails.findCurrentUser();
    	modelMap.addAttribute("institutions", new TreeSet<FinancialInstitution>(user.getInstitutions()));
        return "qif/index";
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public String upload(byte[] input, byte[] investment, String locale, long institution, ModelMap modelMap) {
    	String[] splitted = locale.split("_");
    	Locale currency = new Locale(splitted[0], splitted[1], "");
    	FinancialInstitution financialInstitution = FinancialInstitution.findFinancialInstitution(institution);
    	List<Message> messages = qifService.importQIF(currency, financialInstitution, new ByteArrayInputStream(input), investment != null && investment.length > 0 ? new ByteArrayInputStream(investment) : null);
    	modelMap.addAttribute("messages", messages);
    	return "qif/result";
    }

}
